package com.twq.basic.bigpicture

/**
 * Created by tangweiqun on 2017/11/27.
 * Scala读取文件内容
 */
object Step12 {
  def main(args: Array[String]): Unit = {
    //1、使用scala.io.Source读取文件内容
    //新建一个文件，文件名命名为countchars1.scala，然后在文件中写入如下的代码:
    import scala.io.Source
    if (args.length > 0) {
      for (line <- Source.fromFile(args(0)).getLines())
        println(line.length + " " + line)
    } else
      Console.err.println("Please enter filename")
    //scala -nc countchars1.scala countchars1.scala


    //2、Source.fromFile(args(0)).getLines()返回的Iterator[String]只能访问一次
    //需要使用toList()转成list，就可以无穷次的访问了
    //新建一个文件，文件名命名为countchars2.scala，然后在文件中写入如下的代码:
    import scala.io.Source
    def widthOfLength(s: String) = s.length.toString.length

    if (args.length > 0) {
      val lines = Source.fromFile(args(0)).getLines().toList
      val longestLine = lines.reduceLeft(
        (a, b) => if (a.length > b.length) a else b
      )
      val maxWidth = widthOfLength(longestLine)
      for (line <- lines) {
        val numSpaces = maxWidth - widthOfLength(line)
        val padding = " " * numSpaces
        println(padding + line.length + " | " + line)
      }
    }
    else
      Console.err.println("Please enter filename")
    //scala -nc countchars2.scala countchars2.scala

  }
}
